<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 同盾风险决策API为后端接口
 */
class Fraud {
    private $api_url = "https://api.fraudmetrix.cn/riskService";
    private $partner_code = "tan66";
    private $secret_key = "56edc38349344f8eafc4557772b75b78";
    private $params = array();
    /**
    * $event_id 事件id
    * $token_id 此处填写设备指纹服务的会话标识，和部署设备脚本的token一致
    * $account_login 用户登录账户名
    * $logn_ip 登录ip
    */
    function init($params = array()){
        //准备接口参数
        $this->params = array(
            "partner_code" => $this->partner_code,
            "secret_key" => $this->secret_key,
            "event_id" => $params['event_id'],
            "token_id" => $params['token_id'],//此处填写设备指纹服务的会话标识，和部署设备脚本的token一致
            "account_login" => $params['account_login'],
            "account_mobile" => $params['account_mobile'],
            "ip_address" => $params['ip_address'],
            "state" => $params['state']
        );
        return $this;
    }
    
    /**
    * $timeout 超时时间
    * $connection_timeout 连接超时时间
    */
   function invoke_fraud_api($timeout = 500, $connection_timeout = 500) {
       $options = array(
           CURLOPT_POST => 1,            // 请求方式为POST
           CURLOPT_URL => $this->api_url,      // 请求URL
           CURLOPT_RETURNTRANSFER => 1,  // 获取请求结果
           // -----------请确保启用以下两行配置------------
           CURLOPT_SSL_VERIFYPEER => 1,  // 验证证书
           CURLOPT_SSL_VERIFYHOST => 2,  // 验证主机名
           // -----------否则会存在被窃听的风险------------
           CURLOPT_POSTFIELDS => http_build_query($this->params) // 注入接口参数
       );
       if (defined("CURLOPT_TIMEOUT_MS")) {
           $options[CURLOPT_NOSIGNAL] = 1;
           $options[CURLOPT_TIMEOUT_MS] = $timeout;
       } else {
           $options[CURLOPT_TIMEOUT] = ceil($timeout / 1000);
       }
       if (defined("CURLOPT_CONNECTTIMEOUT_MS")) {
                   $options[CURLOPT_CONNECTTIMEOUT_MS] = $connection_timeout;
       } else {
               $options[CURLOPT_CONNECTTIMEOUT] = ceil($connection_timeout / 1000);
       }
       $ch = curl_init();
       curl_setopt_array($ch, $options);
       if(!($response = curl_exec($ch))) {
           // 错误处理，按照同盾接口格式fake调用结果
           return array(
               "success" => false,
               "reason_code" => "000:调用API时发生错误[".curl_error($ch)."]"
           );
       }
       curl_close($ch);
       return json_decode($response, true);
    }
    
}


